//
//  ShopcarController.m
//  jang
//
//  Created by lee han on 16/04/2017.
//  Copyright © 2017 lee han. All rights reserved.
//

#import "ShopcarController.h"
#import "CommonView.h"
#import "UIView+UIViewExt.h"
#import "ShopcarFootView.h"
#import "UIImageView+WebCache.h"
#import "CRUserData.h"
#import "AddressController.h"

@interface ShopcarController ()

@end

@implementation ShopcarController

-(void)requestShopcar:(NSInteger)page{
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%ld", (long)(page)], @"page",
                                 nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_ShopcarList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [CommonView setNativationBar:self];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"ShopcarCell" bundle:nil] forCellReuseIdentifier:@"ShopcarCell"];

    mListData = [[NSMutableArray alloc] init];
    mProductData = [[NSMutableDictionary alloc] init];
    
//    mFootView = [ShopcarFootView loadFromNib];
//    mFootView.mDelegate = self;
//    
//    [mFootView setMoneyInfo:[self calculateMoney]];
//    
//    CGRect tableRect = self.tableView.frame;
//    CGRect rect = mFootView.frame;
//    rect.origin = CGPointMake(0, tableRect.origin.y + tableRect.size.height - 40);
//    mFootView.frame = rect;
//    [self.view addSubview:mFootView];
//    
//    tableRect.size = CGSizeMake(tableRect.size.width, tableRect.size.width - 40);
//    self.tableView.frame = tableRect;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    mMaxPage = 0;
    mCurrentPage = 1;
    
    for (NSMutableDictionary* info in mListData) {
        [info removeAllObjects];
    }
    [mListData removeAllObjects];
    [mProductData removeAllObjects];
    
    if(self.tabBarController.tabBar.hidden == YES)
        self.tabBarController.tabBar.hidden = NO;
    
    [self requestShopcar: 0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshView{
    mRowCount = [mListData count];
    if(mCurrentPage < mMaxPage){
        mRowCount += 1;
    }
    
    [self.tableView reloadData];
    if(mFootView){
        [mFootView setMoneyInfo:[self calculateMoney]];
    }
}

-(void)onClickMore:(id)sender{
    if(mCurrentPage >= mMaxPage)
        return;
    [self requestShopcar:mCurrentPage];
}

-(NSInteger)calculateMoney{
    NSInteger ret = 0;
    NSInteger count, price;
    for (NSDictionary* info in mListData) {
        if([info objectForKey:@"select"] != nil){
            count = [[info objectForKey:@"count"] integerValue];
            price = [[info objectForKey:@"price"] integerValue];
            ret += (count*price);
        }
    }
    return ret;
}

#pragma mark UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(mCurrentPage < mMaxPage && indexPath.row == mRowCount - 1)
        return 30;
    return 75;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(mFootView == nil){
        mFootView = [ShopcarFootView loadFromNib];
        mFootView.mDelegate = self;
    }
    
    [mFootView setMoneyInfo:[self calculateMoney]];
    return mFootView;
}
//end UITableViewDelegate

#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return mRowCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(mCurrentPage < mMaxPage && indexPath.row == mRowCount - 1){
        UITableViewCell* lastcell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        lastcell.backgroundColor = [UIColor clearColor];
        
        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        
        button.backgroundColor = [UIColor clearColor];
        
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        if(mCurrentPage < mMaxPage){
            [button setTitle:@"点击加载更多" forState:UIControlStateNormal];
        }
        else{
            [button setTitle:@"" forState:UIControlStateNormal];
        }
        
        [button addTarget:self action:@selector(onClickMore:) forControlEvents:UIControlEventTouchUpInside];
        
        [lastcell addSubview:button];
        
        return lastcell;
        
    }
    ShopcarCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ShopcarCell" forIndexPath:indexPath];
   
    cell.mDelegate = self;
    NSDictionary* rdata = [mListData objectAtIndex:indexPath.row];
    NSDictionary* pdata = [mProductData objectForKey:[rdata objectForKey:@"productid"]];
    [cell initWithData:rdata productdata:pdata];
    
    return cell;
}


//end UITableViewDataSource

#pragma mark networkDelegate

- (void)parserResult:(NSDictionary *)response functionType:(NSInteger)type
{
    if (type == NetworkFunctionType_ShopcarList){
        if([[response objectForKey:@"status"] integerValue] == 1){
            mCurrentPage = [[response objectForKey:@"curpage"] integerValue];
            mMaxPage = [[response objectForKey:@"page"] integerValue];
            
            NSArray* adddata = [response objectForKey:@"data"];
            if(![adddata isEqual:[NSNull null]]){
                for (NSDictionary* info in adddata) {
                    NSMutableDictionary* newdata = [NSMutableDictionary dictionaryWithDictionary:info];
                    [newdata setObject:@"1" forKey:@"select"];
                    [mListData addObject:newdata];
                }
            }
            
            NSDictionary* padddata = [response objectForKey:@"pdata"];
            if(![padddata isEqual:[NSNull null]]){
                [mProductData setValuesForKeysWithDictionary:padddata];
            }
            
            [self refreshView];
        }
        else{
            [CommonView addAlertView:self Text:@"获取信息失败"];
        }
    }
}
//end networkDelegate

#pragma mark ShopcalCellDelegate
-(void)onCountChanged:(NSString*)sid Count:(NSInteger)newcount{
    for (NSMutableDictionary* reseverinfo in mListData) {
        if([[reseverinfo objectForKey:@"id"] isEqualToString:sid]){
            [reseverinfo setObject:[NSString stringWithFormat:@"%ld", newcount] forKey:@"count"];
            break;
        }
    }
    if(mFootView){
        [mFootView setMoneyInfo:[self calculateMoney]];
    }
}

-(void)onDelected:(NSString*)sid{
    for (NSMutableDictionary* reseverinfo in mListData){
        if([[reseverinfo objectForKey:@"id"] isEqualToString:sid]){
            [reseverinfo removeAllObjects];
            [mListData removeObject:reseverinfo];
            break;
        }
    }
    [self refreshView];
}
-(void)onClickSelect:(NSString *)sid Selected:(BOOL)isselect{
    for (NSMutableDictionary* reseverinfo in mListData){
        if([[reseverinfo objectForKey:@"id"] isEqualToString:sid]){
            if(isselect){
                [reseverinfo setObject:@"1" forKey:@"select"];
            }
            else{
                [reseverinfo removeObjectForKey:@"select"];
            }
            if(mFootView){
                [mFootView setMoneyInfo:[self calculateMoney]];
            }
            return;
        }
    }
}
//end ShopcalCellDelegate

#pragma mark ShopcarFootViewDelegate
-(void)onClickFootSelect{
    for (NSMutableDictionary* info in mListData) {
        [info setValue:@"1" forKey:@"select"];
    }
    [self refreshView];
}

-(void)onClickFootSubmit{
    [[CRUserData sharedInstance].mOrderData removeAllObjects];
    [[CRUserData sharedInstance].mOrderProductData removeAllObjects];
    for (NSDictionary* info in mListData) {
        if([[info objectForKey:@"select"] integerValue] == 1){
            [[CRUserData sharedInstance].mOrderData addObject:info];
            
            [[CRUserData sharedInstance].mOrderProductData setObject:[mProductData objectForKey:[info objectForKey:@"productid"]] forKey:[info objectForKey:@"productid"]];
        }
    }
    [self performSegueWithIdentifier:@"shopcartoadr" sender:self];
}
//end ShopcarFootViewDelegate

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)prepareForSegue: (UIStoryboardSegue *)segue sender:(id)sender{
    AddressController *destination = segue.destinationViewController;
    [destination setShopcarType];
}
@end
